package com.xianniu.ltc.api;

import cn.devezhao.persist4j.engine.ID;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rebuild.core.UserContextHolder;
import com.rebuild.core.configuration.NavBuilder;
import com.rebuild.core.service.dashboard.charts.ChartsFactory;
import com.rebuild.utils.AppUtils;
import com.xianniu.ltc.model.po.*;
import com.xianniu.ltc.service.ExternalService;
import com.xianniu.ltc.service.ProjectService;
import com.xxl.sso.core.entity.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * @author WangRuiJie
 * @Title: UserAndDepartmentController
 * @Package com.xianniu.ltc.controller
 * @Description: 接收人员+部门关系操作类
 * @date 2021/5/314:27 下午
 */
@Slf4j
@RestController
@RequestMapping(value = "/external")
public class ExternalController {
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ExternalService externalService;

    @PostMapping("/addOrUpdateUserForAuth")
    public ReturnT addOrUpdateUserForAuth(@RequestBody TUserPo po){
        log.info("接收操作台传输的新增/修改用户对应角色，部门信息:{}", JSON.toJSON(po));
        long a = System.currentTimeMillis();
        log.info("当前时间：{}",a);
        ReturnT returnT = externalService.addOrUpdateUserForAuth(po);
        log.info("当前时间：{}",System.currentTimeMillis()-a);
        return returnT;
    }

    /**
     * 接收企业操作台：根据手机号码修改用户的全称，头像，邮箱信息
     * @param po
     * @return
     */
    @PostMapping("/updateLtcUser")
    public ReturnT updateLtcUser(@RequestBody UserUpdatePO po){
        log.info("接收操作台传输的修改用户基础信息:{}", JSON.toJSON(po));
        return externalService.updateLtcUser(po);
    }

    /**
     * 初始化新saasku，修改管理员账号为参数里的手机号
     * @param userPo
     * @return
     */
    @PostMapping("/initUser")
    public ReturnT initUser(@RequestBody LtcInitUserPo userPo){
        String loginName = userPo.getLoginName();
        String tenantCode = userPo.getTenantCode();
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(tenantCode)){
            log.info("初始化新saas库，手机号或者租户编码不能为空");
            return ReturnT.FAIL;
        }
        log.info("初始化新saas库，修改管理员账号为参数里的手机号:{}，租户{}", loginName, tenantCode);
        try{
            return externalService.initUser(loginName, tenantCode);
        }catch (Exception e){
            e.printStackTrace();
            log.info("initUser Exception:{}",e.getMessage());
            return new ReturnT(500, "初始化新saas库异常，请联系管理员");
        }
    }


    /**
     * 根据交付事件ID修改交付事件状态
     * @param request
     * @return
     */
    @PostMapping("/updateJFEnentStatus")
    public ReturnT updateJFEnentStatus(@RequestBody ApiUpdateJFStatusPO po, HttpServletRequest request){
        String tenantCode = po.getSaasCode();
        if (StringUtils.isEmpty(tenantCode)){
            log.info("初始化新saas库，租户编码不能为空");
            return new ReturnT(400, "租户编码不能为空");
        }
        UserContextHolder.setTenant(tenantCode);
        log.info("根据交付事件ID修改交付事件状态：{}", JSON.toJSON(po));
        return externalService.updateJFEnentStatus(po);
    }

    /**
     * 根据采购事件ID修改采购事件状态
     * @param request
     * @return
     */
    @PostMapping("/updateCGEnentStatus")
    public ReturnT updateCGEnentStatus(@RequestBody ApiUpdateJFStatusPO po, HttpServletRequest request){
        String tenantCode = po.getSaasCode();
        if (StringUtils.isEmpty(tenantCode)){
            log.info("初始化新saas库，租户编码不能为空");
            return new ReturnT(400, "租户编码不能为空");
        }
        UserContextHolder.setTenant(tenantCode);
        log.info("根据交付事件ID修改交付事件状态：{}", JSON.toJSON(po));
        return externalService.updateCGEnentStatus(po);
    }

    /**
     * 根据条件分页查询合同/框架协议下的
     * @param request
     * @return
     */
    @PostMapping("/queryDeviceList")
    public ReturnT queryDeviceList(@RequestBody ApiQueryDevicePO po, HttpServletRequest request){
        String tenantCode = po.getSaasCode();
        if (StringUtils.isEmpty(tenantCode)){
            log.info("初始化新saas库，租户编码不能为空");
            return new ReturnT(400, "租户编码不能为空");
        }
        UserContextHolder.setTenant(tenantCode);
        log.info("根据交付事件ID修改交付事件状态：{}", JSON.toJSON(po));
        return externalService.queryDeviceList(po);
    }

    /***************************************** 接收采购云相关接口 开始 *********************************************/

    /**
     * 接收采购云的应急采购订单
     * @param request
     * @return
     */
    @PostMapping("/receivePmsYingJi")
    public ReturnT receivePmsYingJi(@RequestBody TYingjicaigoudingdanPO po, HttpServletRequest request){
        String tenantCode = po.getTenantCode();
        if (StringUtils.isEmpty(tenantCode)){
            log.info("租户编码不能为空");
            return new ReturnT(400, "租户编码不能为空");
        }
        UserContextHolder.setTenant(tenantCode);
        log.info("接收采购云的应急采购订单：{}", JSON.toJSON(po));
        return externalService.receivePmsYingJi(po);
    }

    /**
     * 接收采购云的计划采购订单
     * @param request
     * @return
     */
    @PostMapping("/receivePmsJiHua")
    public ReturnT receivePmsJiHua(@RequestBody TJihuacaigoudingdanshangpinPO po, HttpServletRequest request){
        String tenantCode = po.getTenantCode();
        if (StringUtils.isEmpty(tenantCode)){
            log.info("租户编码不能为空");
            return new ReturnT(400, "租户编码不能为空");
        }
        UserContextHolder.setTenant(tenantCode);
        log.info("接收采购云的计划采购订单：{}", JSON.toJSON(po));
        return externalService.receivePmsJiHua(po);
    }

    /**
     * 接收采购云的维保采购订单
     * @param request
     * @return
     */
    @PostMapping("/receivePmsWeiBao")
    public ReturnT receivePmsWeiBao(@RequestBody TJihuacaigouxiangmuPO po, HttpServletRequest request){
        String tenantCode = po.getTenantCode();
        if (StringUtils.isEmpty(tenantCode)){
            log.info("租户编码不能为空");
            return new ReturnT(400, "租户编码不能为空");
        }
        UserContextHolder.setTenant(tenantCode);
        log.info("接收采购云的维保采购订单：{}", JSON.toJSON(po));
        return externalService.receivePmsWeiBao(po);
    }

    /**
     * 接收采购云的售后采购订单
     * @param request
     * @return
     */
    @PostMapping("/receivePmsShouHou")
    public ReturnT receivePmsShouHou(@RequestBody TCaigoushouhoudingdanshangpinPO po, HttpServletRequest request){
        String tenantCode = po.getTenantCode();
        if (StringUtils.isEmpty(tenantCode)){
            log.info("租户编码不能为空");
            return new ReturnT(400, "租户编码不能为空");
        }
        UserContextHolder.setTenant(po.getTenantCode());
        log.info("接收采购云的售后采购订单：{}", JSON.toJSON(po));
        return externalService.receivePmsShouHou(po);
    }

    /**
     * 接收采购云的项目类付款
     * @param request
     * @return
     */
    @PostMapping("/receivePmsItemPayment")
    public ReturnT receivePmsItemPayment(@RequestBody TXiangmuleifukuanPO po, HttpServletRequest request){
        String tenantCode = po.getTenantCode();
        if (StringUtils.isEmpty(tenantCode)){
            log.info("租户编码不能为空");
            return new ReturnT(400, "租户编码不能为空");
        }
        UserContextHolder.setTenant(tenantCode);
        log.info("接收采购云的项目类付款：{}", JSON.toJSON(po));
        return externalService.receivePmsItemPayment(po);
    }

    /***************************************** 接收采购云相关接口 结束 *********************************************/
    @PostMapping("/projectPage")
    public ReturnT projectPage(@RequestBody ProjectQueryPO param){
        UserContextHolder.setTenant(param.getTenantCode());
        return projectService.projectPage(param);
    }

    /**
     * 外部 修改项目管理
     * @param po
     * @return
     */
    @PostMapping("/projectUpdate")
    public ReturnT projectUpdate(@RequestBody ProjectUpdatePO po){
        log.info("修改项目管理参数：{}", JSON.toJSON(po));
        if (ObjectUtil.isNull(po)){
            return new ReturnT(500,"参数不能为空");
        }
        if (ObjectUtil.isEmpty(po.getProjectId()) || ObjectUtil.isEmpty(po.getTenantCode())){
            return new ReturnT(500,"参数错误");
        }
        UserContextHolder.setTenant(po.getTenantCode());
        return projectService.projectUpdate(po);
    }

    @PostMapping("/projectDetail")
    public ReturnT projectDetail(@RequestBody ProjectQueryPO param){
        UserContextHolder.setTenant(param.getTenantCode());
        return projectService.projectDetail(param);
    }

    /**
     * API-查询项目列表
     * @param param
     * @return
     */
    @PostMapping("/projectList")
    public ReturnT projectList(@RequestBody ProjectQueryPO param){
        log.info("New-查询项目管理列表参数：{}", JSON.toJSON(param));
        UserContextHolder.setTenant(param.getTenantCode());
        return projectService.projectList(param);
    }

    /**
     * API-查询项目每个阶段的数量
     * @param param
     * @return
     */
    @PostMapping("/projectCount")
    public ReturnT projectCount(@RequestBody ProjectCountPO param){
        log.info("New-查询项目每个阶段的数量参数：{}", JSON.toJSON(param));
        UserContextHolder.setTenant(param.getTenantCode());
        return projectService.projectCount(param);
    }

    /**
     * 根据项目ID查询项目中的商机信息
     * @param param
     * @return
     */
    @PostMapping("/selectNiche")
    public ReturnT selectNiche(@RequestBody ProjectQueryRelatedPO param){
        UserContextHolder.setTenant(param.getTenantCode());
        return projectService.selectNiche(param);
    }

    /**
     * 根据项目ID查询项目中的客户及联系人信息
     * @param param
     * @return
     */
    @PostMapping("/selectCustomerInfo")
    public ReturnT selectCustomerInfo(@RequestBody ProjectQueryRelatedPO param){
        UserContextHolder.setTenant(param.getTenantCode());
        return projectService.selectCustomerInfo(param);
    }

    /**
     * 根据项目ID查询对应实体的列表数据
     * @param param
     * @return
     */
    @PostMapping("/selectEntityInfoList")
    public ReturnT selectEntityInfoList(@RequestBody ProjectQueryRelatedPO param){
        UserContextHolder.setTenant(param.getTenantCode());
        return projectService.selectEntityInfoList(param);
    }

    /**
     * 根据项目查询报表数据
     * @param param
     * @return
     */
    @PostMapping("/selectProjectReport")
    public ReturnT selectProjectReport(@RequestBody ProjectReportPO param){
        UserContextHolder.setTenant(param.getTenantCode());
        return projectService.selectProjectReport(param);
    }


    /***************************************** 采购云询价相关接口 开始 *********************************************/

    /**
     * 采购云发布询价查询销售云的销售合同数据
     * @param request
     * @return
     */
    @PostMapping("/queryRbHeTong")
    public ReturnT queryRbHeTong(@RequestBody QueryRbHeTongPO po, HttpServletRequest request){
        String tenantCode = po.getTenantCode();
        if (StringUtils.isEmpty(tenantCode)){
            log.info("租户编码不能为空");
            return new ReturnT(400, "租户编码不能为空");
        }
        UserContextHolder.setTenant(tenantCode);
        log.info("采购云发布询价查询销售云的销售合同数据：{}", JSON.toJSON(po));
        return externalService.queryRbHeTong(po);
    }

    /**
     * 采购云发布询价新增报价协同数据
     * @param request
     * @return
     */
    @PostMapping("/createInquiryToLtc")
    public ReturnT createInquiryToLtc(@RequestBody TBaojiaxietongPO po, HttpServletRequest request){
        String tenantCode = po.getTenantCode();
        if (StringUtils.isEmpty(tenantCode)){
            log.info("租户编码不能为空");
            return new ReturnT(400, "租户编码不能为空");
        }
        UserContextHolder.setTenant(tenantCode);
        log.info("采购云发布询价新增报价协同数据：{}", JSON.toJSON(po));
        return externalService.createInquiryToLtc(po);
    }

    /***************************************** 采购云询价相关接口 结束 *********************************************/

    /**
     * 外部：定时新增项目报表数据
     * @param poList
     * @return
     */
    @PostMapping("/projectReportDayData")
    public ReturnT projectReportDayData(@RequestBody List<AddProjectReportPO> poList){
        if (CollectionUtils.isEmpty(poList)){
            log.info("参数不能为空");
            return new ReturnT(500, "参数不能为空");
        }
        String tenantCode = poList.get(0).getTenantCode();
        if (StringUtils.isEmpty(tenantCode)){
            log.info("租户编码不能为空");
            return new ReturnT(400, "租户编码不能为空");
        }
        UserContextHolder.setTenant(tenantCode);
        log.info("定时新增项目报表数据：{}", JSON.toJSON(poList));
        try{
            return externalService.projectReportDayData(poList);
        }catch (Exception e){
            e.printStackTrace();
            log.info("projectReportDayData Exception:{}",e.getMessage());
            return new ReturnT(500, "定时新增项目报表数据异常");
        }
    }

    /***************************************** 供应商数据同步 开始 *********************************************/

    /**
     * 新增/修改企业供应商信息
     * @param po
     * @return
     */
    @PostMapping("/receiveSupplierInfo")
    public ReturnT receiveSupplierInfo(@RequestBody List<AddSupplierPO> po){
        if (CollectionUtils.isEmpty(po)){
            log.info("新增/修改企业供应商信息参数不能为空");
            return new ReturnT(400, "新增/修改企业供应商信息参数不能为空");
        }
        log.info("新增/修改企业供应商信息：{}", JSON.toJSON(po));
        return externalService.receiveSupplierInfo(po);
    }

    /**
     * 删除企业供应商信息
     * @param po
     * @return
     */
    @PostMapping("/deleteSupplierInfo")
    public ReturnT deleteSupplierInfo(@RequestBody List<DeleteSupplierPO> po){
        if (CollectionUtils.isEmpty(po)){
            log.info("删除企业供应商信息参数不能为空");
            return new ReturnT(400, "删除企业供应商信息参数不能为空");
        }
        log.info("删除企业供应商信息参数：{}", JSON.toJSON(po));
        return externalService.deleteSupplierInfo(po);
    }

    /***************************************** 供应商数据同步 结束 *********************************************/

    /***************************************** 交付云-接收首检设备明细接口 开始 *********************************************/
    /**
     * 接收交付云首检设备明细接口
     * @param po
     * @return
     */
    @PostMapping("/receiveTsEquipmentDetails")
    public ReturnT receiveTsEquipmentDetails(@RequestBody List<LtcInspectionPO> po){
        if (CollectionUtils.isEmpty(po)){
            log.info("接收交付云首检设备明细接口不能为空");
            return new ReturnT(400, "接收交付云首检设备明细接口不能为空");
        }
        // 由于交付云触发点没有token标识，所以走无token路径
        UserContextHolder.setTenant(po.get(0).getSaasCode());
        log.info("接收交付云首检设备明细接口：{}", JSON.toJSON(po));
        return externalService.receiveTsEquipmentDetails(po);
    }

    /***************************************** 交付云-接收首检设备明细接口 结束 *********************************************/
    @PostMapping("/saveMessage")
    public ReturnT saveMessage(@RequestBody JSONObject po){
        if(Objects.nonNull(po)){
            log.info("->留资内容:{}",JSONObject.toJSONString(po));
        }else{
            log.info("->留资内容是空的.");
        }
        return ReturnT.SUCCESS;
    }
}
